import { getRouters } from '@/api/menu'
import { defineStore } from 'pinia'
import Layout from '@/layout/index.vue'
import type { RouteRecordRaw } from 'vue-router'

import useUserStore from '@/store/modules/user'
import { reactive } from 'vue'

const usePermissionRouter = defineStore('PermissionRouter', {
  state: () => ({
    addRoutes: [],
  }),
  actions: {
    // 生成路由
    GenerateRoutes() {
      return new Promise((resolve) => {
        getRouters().then((res) => {
          const rdata = JSON.parse(JSON.stringify(res.data))
          const rewriteRoutes: Array<RouteRecordRaw> = this.filterAsyncRouter(
            rdata,
            false,
            true,
          )
          this.addRoutes = useUserStore().menuRouts.concat(reactive(rewriteRoutes))
          resolve(rewriteRoutes)
        })
      })
    },
    // 遍历后台传来的路由字符串，转换为组件对象
    filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
      return asyncRouterMap.filter((route) => {
        if (type && route.children) {
          route.children = this.filterChildren(route.children)
        }
        if (route.component) {
          if (route.component === 'Layout') {
            route.component = Layout
          } else {
            route.component = loadView(route.component)
          }
        }
        if (route.children != null && route.children && route.children.length) {
          route.children = this.filterAsyncRouter(route.children, route, type)
        } else {
          delete route['children']
          delete route['redirect']
        }
        return true
      })
    },
    filterChildren(childrenMap, lastRouter = false) {
      var children = []
      childrenMap.forEach((el) => {
        el.path = el.path
        if (
          el.children &&
          el.children.length &&
          el.component === 'ParentView'
        ) {
          children = children.concat(this.filterChildren(el.children, el))
        } else {
          children.push(el)
        }
      })
      console.log(children);
      
      return children
    },
  },
})

const modules = import.meta.glob('@/**/*.vue')

export const loadView = (view) => {
  if (import.meta.env.MODE === 'development') {
    const importPage = modules[view.replace('@', '/src')]
    // return import.meta.glob('@/views/**/*.vue')
    // console.log(importPage);
    return importPage
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`)
  }
}

export default usePermissionRouter
